package com.ch4;

import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author woldier
 * @version 1.0
 * @description 买票问题 线程不安全
 * @date 2023/4/19 16:52
 **/
@Slf4j(topic = "c.Thread")
public class Demo04 {

    public static void main(String[] args) {
        TicketWindow ticketWindow = new TicketWindow(2000);
        List<Thread> threads = new Vector<>(); //存放线程
        List<Integer> count = new Vector<>(); //存放买票数目,这里没有使用int 类型近累加是因为可能出现先线程安全问题

        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(
                    () -> count.add(ticketWindow.getTicket(randomAmount()))
            );
            threads.add(thread);
            thread.start();
        }
        threads.forEach(e -> {  //线程jion
            try {
                e.join();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        });

        log.debug("卖出的总数为 {}",count.stream().mapToInt(e -> e).sum() );
        log.debug("剩余的票数为{}",ticketWindow.getCount());
    }

    // Random 为线程安全
    static Random random = new Random(); // 随机 1~5

    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }

}

class TicketWindow {
    private int count;

    public int getCount() {
        return count;
    }

    public TicketWindow(int count) {
        this.count = count;
    }

    public  int getTicket(int num) {
        if (count > num) {
            count = count - num;
            return num;
        } else
            return 0;
    }
}